from django.http import HttpResponse
from django.shortcuts import redirect, render
from SimpleBlog1903 import models 
import datetime

data = []
i = 1
while i<11:
    data.append({
        'title':'标题'+str(i),
        'content': '这是第'+str(i) + '条数据',
        'id': i
    })
    i=i+1

def list(request):
    d = models.News.objects.all()
    return render(request,'list.html',{'data':d})

def show(request, id):
    # for model in data:
    #     if id == str(model['id']):
    intId = int(id)
    model = models.News.objects.filter(pk = intId)
    if len(model) > 0:
        return render(request, 'show.html', {'model':model[0]})
    return HttpResponse("数据不存在")

def add(request):
    return render(request, 'add.html')

def addPost(request):
    duixiang = models.News()
    duixiang.Title = request.POST['title']
    duixiang.Content = request.POST['content']
    duixiang.CreationTime = datetime.datetime.now()
    duixiang.save()
    return redirect('/list/')
    
    # id = 1
    # count = len(data)
    # if count>0:
    #     id = data[count - 1]['id']

    # model = {
    #     'title': request.POST['title'],
    #     'content': request.POST['content'],
    #     'id': id
    # }
    # data.append(model)
    # return redirect('/list/')

def edit(request, id):
    # for model in data:
    #     if id == str(model['id']):
    #         return render(request, 'edit.html', {'model':model})
    # return HttpResponse("没有找到该数据")
    m = models.News.objects.get(Id = id)
    return render(request, 'edit.html', {'model':m})

def editPost(request, id):
    # for model in data:
    #     if id == str(model['id']):
    #         model['title'] = request.POST['title']
    #         model['content'] = request.POST['content']
    #         break
    m = models.News.objects.get(Id = id)
    m.Title = request.POST['title']
    m.Content = request.POST['content']
    m.save()
    return redirect('/list/')

def delete(request, id):
    # for model in data:
    #     if id == str(model['id']):
    #         data.remove(model)
    intId = int(id)
    m = models.News.objects.get(Id = intId)
    m.delete()
    return redirect('/list/')